package cn.app.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.app.entity.AppCategory;
import cn.app.entity.AppInfo;
import cn.app.entity.AppVersion;
import cn.app.entity.DataDictionary;
import cn.app.entity.DevUser;
import cn.app.service.AppCategoryService;
import cn.app.service.AppInfoService;
import cn.app.service.AppVersionService;
import cn.app.service.DataDictionaryService;
import cn.app.utils.AppDictionary;
import cn.app.utils.PageBean;

@Controller
@RequestMapping("/devApp")
public class DevAppController {
	private static final String DevUser = null;
	//字典表的service
	@Autowired
	private DataDictionaryService dataDictionaryService;
	//分类表的service
	@Autowired
	private AppCategoryService appCategoryService;
	//appInfo表的service
	@Autowired
	private AppInfoService appInfoService;
	//app版本信息表的service
	@Autowired
	private AppVersionService appVersionService;
	//跳转到开发者平台主页
	@RequestMapping("/disMain")
	public String disMain(){
		return "dev/main";
	}
	
	//=========================================================================================
	//跳转到app维护页面
	@RequestMapping("/appInfoList")
	public String appInfoList(Model model,
							  @RequestParam(name="currentPage",required=false)Integer currentPage,
							  @RequestParam(name="softwarename",required=false)String softwarename,
							  @RequestParam(name="status",required=false)String status,
							  @RequestParam(name="flatformid",required=false)String flatformid,
							  @RequestParam(name="categorylevel1",required=false)String categorylevel1,
							  @RequestParam(name="categorylevel2",required=false)String categorylevel2,
							  @RequestParam(name="categorylevel3",required=false)String categorylevel3){
		//1.将条件查询的数据返回给页面..
		//1.1.1查询出app的状态的显示数据和返回的value值..
		List<DataDictionary> appStatusList = dataDictionaryService.findAppDictionary(AppDictionary.APP_STATUS);
		//1.1.2将查询出的app的状态的数据放到model中.
		model.addAttribute("appStatusList", appStatusList);
		
		//1.2.1查询出app的所属平台数据..
		List<DataDictionary> appFlatFormList = dataDictionaryService.findAppDictionary(AppDictionary.APP_FLATFORM);
		//1.1.2将查询出的app的状态的数据放到model中.
		model.addAttribute("appFlatFormList", appFlatFormList);
		
		//1.3.1查询出app的一级分类数据.
		List<AppCategory> appCategoryLevelOneList = appCategoryService.findAppCategory(AppDictionary.APP_CATEGORY_LEVEL_ONE);
		//1.3.2将查询出的app的分类的数据放到model中.
		model.addAttribute("appCategoryLevelOneList", appCategoryLevelOneList);
		
		//====================================================================================================
		
		//2.将app信息回给页面..
		//2.1需要根据条件查询出全部数据
		//封装全部的条件
		Map<String,Object> appInfoCondition = new HashMap<>();
		appInfoCondition.put("currentPage", currentPage);
		appInfoCondition.put("softwarename", softwarename);
		appInfoCondition.put("status", status);
		appInfoCondition.put("flatformid", flatformid);
		appInfoCondition.put("categorylevel1", categorylevel1);
		appInfoCondition.put("categorylevel2", categorylevel2);
		appInfoCondition.put("categorylevel3", categorylevel3);
		//2.2要根据分页查询数据..
		//调用appInfoservice层的方法,查询指定的app信息
		PageBean<AppInfo> pageBean = appInfoService.findAppInfoByCondition(appInfoCondition);
		//2.3放到model中
		model.addAttribute("pageBean", pageBean);
		
		
		//=====================================================================================================
		
		//问题:当执行条件查询之后,条件的数据没有回显
		//3.1:将页面传过来的数据,再次返回给页面,数据在查询APP信息的时候,已经将查询的条件都封装到map中,直接讲map返回
		model.addAttribute("appInfoCondition", appInfoCondition);
		//问题:状态,所属平台,一级分类都可以数据回显,但是二级分类和三级分类的下拉列表,没有数据,无法回显查询条件
		//解决:既然没有数据,给他.
		//1.分别查询对应的二级分类的数据和三级分类数据
		//1.1获得二级分类数数据集合
		//放第一此访问的时候,categorylevel1传来的数据是null ,所以当categorylevel1==null的时候,不去查询.
		if(categorylevel1 != null){
			List<AppCategory> appCategoryTwoList = appCategoryService.findAppCategory(categorylevel1);
			model.addAttribute("appCategoryTwoList", appCategoryTwoList);
		}
		//1.2对应获得三级分类数数据集合
		if(categorylevel2 != null){
			List<AppCategory> appCategoryThreeList = appCategoryService.findAppCategory(categorylevel2);
			model.addAttribute("appCategoryThreeList", appCategoryThreeList);
		}
		//讲查询出的数据放入model中,返回给页面
		return "dev/appInfoList";
	}
	
	
	//===============================================================================================
	
	//三级联动..
	@RequestMapping("/findAppCategoryByParentId")
	public @ResponseBody List<AppCategory> findAppCategoryByParentId(@RequestBody Map<String,String> map){
		//获得parentId
		String parentId = map.get("levelId");
		//获得parentId对应的下属分类集合
		List<AppCategory> appCategoryList = appCategoryService.findAppCategory(parentId);
		//返回json数据
		return appCategoryList;
	}
	
	//===============================================================================================
	
	//跳转到APP添加页面
	@RequestMapping("/disAppInfoAdd")
	public String disAppInfoAdd(Model model){
		//1.页面需要两个下拉框的数据
		//1.1所属平台
		List<DataDictionary> appFlatFormList = dataDictionaryService.findAppDictionary(AppDictionary.APP_FLATFORM);
		model.addAttribute("appFlatFormList", appFlatFormList);
		//1.2一级分类
		List<AppCategory> appCategoryLevelOneList = appCategoryService.findAppCategory(AppDictionary.APP_CATEGORY_LEVEL_ONE);
		model.addAttribute("appCategoryLevelOneList", appCategoryLevelOneList);
		
		return "dev/appInfoAdd";
	}
	
	//===============================================================================================
	//异步校验APKName是否重复
	@RequestMapping("/checkAPKName")
	public @ResponseBody String checkAPKName(String apkname){
		Integer flag = appInfoService.findAppInfoByAPKName(apkname);
		return flag+"";
	}
	
	//===============================================================================================
	
	//执行添加APP信息操作.
	@RequestMapping("/appInfoAdd")
	public String appInfoAdd(AppInfo appInfo,MultipartFile picFile,Model model,HttpSession session) throws Exception{
		//1.要求图片的格式必须是.jpg|.png|.jpeg
		//1.1获得图片的后缀类型
		//1.1.1获得图片的原名字
		String originalFilename = picFile.getOriginalFilename();
		//1.1.2截取获得图片的后缀		获得最后一个.的位置,然后截取
		String typeName = originalFilename.substring(originalFilename.lastIndexOf("."));
		if(typeName.equals(".jpg") || typeName.equals(".png") || typeName.equals(".jpeg")){
			//满足图片类型后缀
			//2.要求图片的大小不能大于5M
			//2.2获得图片的大小
			Long size = picFile.getSize();
			//2.2.1判断图片的大小不能大于5M
			if(size < 5242880L){
				//两个要求都满足,就开始保存图片
				//3.1给图片搞一个新名字
				String newName = UUID.randomUUID().toString() + typeName;
				//3.2图片保存到本地
				picFile.transferTo(new File("D:\\Picture\\" + newName));
				//3.3给AppInfo对象赋值.
				//3.3.1保存图片的服务器路径
				appInfo.setLogopicpath("http://localhost:8080/pic/" + newName);
				//3.3.2保存图片的绝对路径
				appInfo.setLogolocpath("D:\\Picture\\" + newName);
			}else{
				//图片大小不满足要求
				model.addAttribute("fileInfo", "图片的大小不能大于5M");
				return "/dev/appInfoAdd";
			}
		}else{
			//图片类型不匹配...
			model.addAttribute("fileInfo", "图片的类型必须是.jpg|.png|.jpeg中的一种.");
			return "/dev/appInfoAdd";
		}
		//--------------------------------------------------------------------------
		//4.需要获得到的数据
		//4.1获得到session域中对象的id
		DevUser devUser = (DevUser) session.getAttribute("devUser");
		Long devid = devUser.getId();
		//4.1.1:devId-->开发者的id-->可以去session域去中拿..
		appInfo.setDevid(devid);
		//4.1.2:createId-->添加者的的id-->可以去session域去中拿..
		appInfo.setCreatedby(devid);
		
		//----------------------------------------------------------------------------
		//5.执行保存
		Integer count = appInfoService.saveAppInfo(appInfo);
		if(count > 0){
			//添加成功..
			return "redirect:/devApp/appInfoList";
		}else{
			//添加失败..
			model.addAttribute("saveAppInfo", "系统错误,请跟管理员联系.");
			return "/dev/appInfoAdd";
		}
		
		
	}
	
	
	//===============================================================================================
	//跳转到修改页面
	@RequestMapping("/disAppInfoUpdate/{id}")
	public String disAppInfoUpdate(@PathVariable("id")String id,Model model){
		//查询被修改的APP的信息
		AppInfo appInfo = appInfoService.findAppInfoById(id);
		model.addAttribute("appInfo", appInfo);
		//1.页面需要两个下拉框的数据
		//1.1所属平台
		List<DataDictionary> appFlatFormList = dataDictionaryService.findAppDictionary(AppDictionary.APP_FLATFORM);
		model.addAttribute("appFlatFormList", appFlatFormList);
		//1.2一级分类
		List<AppCategory> appCategoryLevelOneList = appCategoryService.findAppCategory(AppDictionary.APP_CATEGORY_LEVEL_ONE);
		model.addAttribute("appCategoryLevelOneList", appCategoryLevelOneList);
		//1.3二级分类
		List<AppCategory> appCategoryTwoList = appCategoryService.findAppCategory(appInfo.getCategorylevel1()+"");
		model.addAttribute("appCategoryTwoList", appCategoryTwoList);
		//1.4三级分类
		List<AppCategory> appCategoryThreeList = appCategoryService.findAppCategory(appInfo.getCategorylevel2()+"");
		model.addAttribute("appCategoryThreeList", appCategoryThreeList);
		return "dev/appInfoUpdate";
	}
	
	
	
	//===============================================================================================
	//修改APP基础信息
	@RequestMapping("/appInfoUpdate")
	public String appInfoUpdate(AppInfo appInfo,MultipartFile picFile,Model model,HttpSession session) throws Exception{
		//1.判断用户是否传来新图片
		if(picFile.getSize() > 0L){
			//传来了新图片.
			//1.要求图片的格式必须是.jpg|.png|.jpeg
			//1.1获得图片的后缀类型
			//1.1.1获得图片的原名字
			String originalFilename = picFile.getOriginalFilename();
			//1.1.2截取获得图片的后缀		获得最后一个.的位置,然后截取
			String typeName = originalFilename.substring(originalFilename.lastIndexOf("."));
			if(typeName.equals(".jpg") || typeName.equals(".png") || typeName.equals(".jpeg")){
				//满足图片类型后缀
				//2.要求图片的大小不能大于5M
				//2.2获得图片的大小
				Long size = picFile.getSize();
				//2.2.1判断图片的大小不能大于5M
				if(size < 5242880L){
					//两个要求都满足,就开始保存图片
					//3.1给图片搞一个新名字
					String newName = UUID.randomUUID().toString() + typeName;
					//3.2图片保存到本地
					picFile.transferTo(new File("D:\\Picture\\" + newName));
					//3.3给AppInfo对象赋值.
					//3.3.1保存图片的服务器路径
					appInfo.setLogopicpath("http://localhost:8080/pic/" + newName);
					//3.3.2保存图片的绝对路径
					appInfo.setLogolocpath("D:\\Picture\\" + newName);
				}else{
					//图片大小不满足要求
					model.addAttribute("fileInfo", "图片的大小不能大于5M");
					return "forward:/devApp/disAppInfoUpdate/"+appInfo.getId();
				}
			}else{
				//图片类型不匹配...
				model.addAttribute("fileInfo", "图片的类型必须是.jpg|.png|.jpeg中的一种.");
				return "forward:/devApp/disAppInfoUpdate/"+appInfo.getId();
			}
		}
		//上传图片
		//-------------------------------------------------------------------------------
		//执行修改操作.
		//修改时,需要给修改时间,和修改人的字段赋值.
		//4.需要获得到的数据
		//4.1获得到session域中对象的id
		DevUser devUser = (DevUser) session.getAttribute("devUser");
		Long devid = devUser.getId();
		appInfo.setModifyby(devid);
		//调用业务层方法进行修改操作..
		Integer count = appInfoService.updateAppInfo(appInfo);
		if(count > 0){
			//修改成功
			return "redirect:/devApp/appInfoList";
		}else{
			//修改失败
			//图片类型不匹配...
			model.addAttribute("updateInfo", "修改失败,系统正在更新.....");
			return "forward:/devApp/disAppInfoUpdate/"+appInfo.getId();
		}
	}
	
	//===============================================================================================
	//跳转到APP版本添加页面
	@RequestMapping("/disAppVersionAdd/{id}")
	public String disAppVersionAdd(@PathVariable("id") Integer id,Model model){
		//1.查询出APP对应的版本信息
		List<AppVersion> appVersionList = appVersionService.findAllByAppId(id,AppDictionary.PUBLISH_STATUS);
		//2.将数据放入model中
		model.addAttribute("appVersionList", appVersionList);
		//3.讲APP的id放入model中,方便调用
		model.addAttribute("appId", id);
		//3.返回页面
		return "/dev/appVersionAdd";
	}
	
	
	//===============================================================================================
	//添加app的新版本
	@RequestMapping("/appVersionAdd")
	public String appVersionAdd(AppVersion appVersion,MultipartFile apkFile,Model model,HttpSession session) throws Exception{
		//1.判断用户是否传来了apk文件.
		if(apkFile.getSize() > 0){
			//用户传了
			//在做一个判断,判断是否是apk文件
			//截取文件的后缀类型
			String originalFilename = apkFile.getOriginalFilename();
			String type = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase().trim();
			if(type.equals(".apk")){
				//封装APK名称.因为APK下载文件的名字规定是  apkname-versionno .apk
				//1.appinfo表中的apkName.
				String apkName = appInfoService.findAPKNameById(appVersion.getAppid());
				//2.版本号
				String versionno = appVersion.getVersionno();
				//3.newName新名字
				String newName = apkName + "-" + versionno +".apk";
				//4.赋值apk文件到虚拟路径
				apkFile.transferTo(new File("D:/Picture/" + newName));
				//5.向appVersion中封装数据
				//5.1apk名字
				appVersion.setApkfilename(newName);
				//5.2apk存储的绝对路径
				appVersion.setApklocpath("D:/Picture/" + newName);
				//5.3apk下载的路径
				appVersion.setDownloadlink("http://localhost:8080/pic/" + newName);
			}else{
				//文件不是APk
				//用户没有传入apk文件
				model.addAttribute("addVersionInfo", "添加失败,文件类型只能是apk文件.");
				return "forward:/devApp/disAppVersionAdd/"+appVersion.getAppid();
			}
		}else{
			//用户没有传入apk文件
			model.addAttribute("addVersionInfo", "添加失败,没有上传APK文件");
			return "forward:/devApp/disAppVersionAdd/"+appVersion.getAppid();
		}
		
		//------------------------------------------------------------------------------------------
		
		//向appVersion中封装当前用户id数据
		DevUser devUser = (cn.app.entity.DevUser) session.getAttribute("devUser");
		appVersion.setCreatedby(devUser.getId());
		//保存数据.添加app新版本
		Integer count = appVersionService.saveAppVersion(appVersion);
		if(count > 0 && appVersion.getId() != null){
			//---------------------------------------------------------------------------------------------
			//需要讲刚刚添加进去的版本信息的主键id在app_info表中进行修改.
			//修改app_info表中的versionid
			appInfoService.updateVersionId(appVersion.getAppid(),appVersion.getId());
			return "redirect:/devApp/appInfoList";
		}else{
			//用户没有传入apk文件
			model.addAttribute("addVersionInfo", "系统错误,请稍后再试...");
			return "forward:/devApp/disAppVersionAdd/"+appVersion.getAppid(); 
		}
		
	}
	
	//===============================================================================================
	
	
	
	
}
